package com.xiaoran.actiiveNIO.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQMessageAudit;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.AsyncCallback;

import javax.jms.*;
import java.util.UUID;

public class JmsProduce {
    public static final String ACTIVEMQ_URL="tcp://192.168.171.128:61616";
    public static final String QUEUE_NAMQ="queue-cluster";
    public static void main(String args[]) throws JMSException {
        //1创建连接工场，，按照给定的url地址，采用默认的用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //开启异步发送
        activeMQConnectionFactory.setUseAsyncSend(true);
        //2通过连接工厂获得连接，获得connection并启动
          Connection connection = activeMQConnectionFactory.createConnection();
          connection.start();
          //3.创建会话session
            Session session= connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //4.创建目的地
            Queue queue=session.createQueue(QUEUE_NAMQ);
            //5.创建消息生场者,指定目的地
           ActiveMQMessageProducer activeMQMessageProducer=(ActiveMQMessageProducer) session.createProducer(queue);
           //开启事务持久化
        activeMQMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
           //6，通过使用消息的生产者发送3条信息到队列；
            for (int i=1;i<=3;i++){
                //7，创建消息
                 TextMessage textMessage=session.createTextMessage("cluster msg---------"+i);
                //设置ID
                textMessage.setJMSMessageID(UUID.randomUUID().toString()+"------orderAtguigu");
                //获取ID
                String msid=textMessage.getJMSMessageID();
                //设置可以发送消息的回调函数
                activeMQMessageProducer.send(textMessage, new AsyncCallback() {
                    @Override
                    public void onSuccess() {
                        System.out.println("----"+msid+"has bean ok send");
                    }
                    @Override
                    public void onException(JMSException exception) {
                        System.out.println("-----"+msid+"fail to send  mq");
                    }
                });

            }
        activeMQMessageProducer.close();
            session.close();
            connection.close();
            System.out.println("****消息发布到MQ完成");


    }


}
